import kotlin.reflect.*

class Memomize<T,R>(val func:(T)->R) {
    var cache = mutableMapOf<T,R>()
    operator fun getValue(thisRef:Any?,property:KProperty<*>) = {n:T -> cache.getOrPut(n){func(n)}}
}

val pricesMap = mapOf(1 to 2,2 to 4,3 to 6,4 to 7,5 to 10,6 to 17,7 to 17)

val maxPrice: (Int)->Int by Memomize{
    length:Int -> val priceAtLength = pricesMap.getOrDefault(length,0)
                  (1 until length).fold(priceAtLength){
                      max,curLength -> val cutPrice = maxPrice(curLength) + maxPrice(length - curLength)
                      Math.max(cutPrice,max) 
                  }
}

for (i in 1..10){
    println("For length $i maxPrice is ${maxPrice(i)}")
}